package middleware

import (
	"errors"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
)

type Claims struct { //从JWT token中解析出claims
	PhoneNumber string `json:"phone_number"`
	HasRenewal  bool   `json:"has_renewal"` // 添加续约状态字段
	jwt.StandardClaims
}

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"success": false,
				"message": "未提供认证token",
			})
			c.Abort()
			return
		}

		// 将 Authorization 头部的值按照空格分割两部分：前缀“Bearer”和随后的token字符串。
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"success": false,
				"message": "token格式错误",
			})
			c.Abort()
			return
		}

		claims, err := parseToken(parts[1])
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"success": false,
				"message": "无效的token",
			})
			c.Abort()
			return
		}

		// 将电话号码和续约状态存储在上下文中
		c.Set("phone_number", claims.PhoneNumber)
		c.Set("has_renewal", claims.HasRenewal)
		c.Next()
	}
}

// parseToken解析JWT token字符串，验证其有效性，并返回一个Claims对象
func parseToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("jwt_secret"), nil // 实际的密钥
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, errors.New("invalid token")
}
